package com.lalameow.common.gui;

import java.util.ListIterator;

/**
 * Author: SettingDust.
 * Date: 2018/5/27.
 */
public class ContainerIterator implements ListIterator<Component> {
    private final Container container;
    private int nextIndex;
    private Boolean lastDirection; // true = forward, false = backward, null = haven't moved yet

    ContainerIterator(Container container, int nextIndex) {
        this.container = container;
        this.nextIndex = nextIndex;
    }

    ContainerIterator(Container container) {
        this(container, 0);
    }

    @Override
    public boolean hasNext() {
        return nextIndex < container.getSize();
    }

    @Override
    public Component next() {
        lastDirection = true;
        return container.get(nextIndex++);
    }

    @Override
    public boolean hasPrevious() {
        return nextIndex > 0;
    }

    @Override
    public Component previous() {
        lastDirection = false;
        return container.get(--nextIndex);
    }

    @Override
    public int nextIndex() {
        return nextIndex;
    }

    @Override
    public int previousIndex() {
        return nextIndex - 1;
    }

    @Override
    public void remove() {
        container.remove(nextIndex);
        if (nextIndex >= container.getSize())
            nextIndex = container.getSize() - 1;
    }

    @Override
    public void set(Component component) {
        if (lastDirection == null) {
            throw new IllegalStateException("No current item!");
        }
        int i = lastDirection ? nextIndex - 1 : nextIndex;
        container.set(i, component);
    }

    @Override
    public void add(Component component) {
        container.add(component);
    }
}
